﻿(function () {
    var myApp = angular.module('MyControllers');

    // 计划所需控制器
    myApp.controller('photoPlanController', ['$scope', '$http', '$modal', 'photoService', 'utils', function ($scope, $http, $modal, service, utils) {
        $scope.getList = function () {
            service.getPlanList($scope.planType).success(function (data) {
                $scope.list = data;
            });
        };

        $scope.official = function () {
            $scope.planType = 0;
            $scope.getList();
        };

        $scope.imatate = function () {
            $scope.planType = 1;
            $scope.getList();
        };

        $scope.detail = function (model) {
            $scope.loadingState = true;

            var parameter = {
                planId: model.examPlanInfoID,
                planName: model.examPlanName
            };

            utils.encrypt(JSON.stringify(parameter)).success(function (data) {
                if (data.resultType == 'Success') {
                    window.location.href = '#/photo/list?parameter=' + data.appendData;
                } else {
                    utils.notify(data.message, 'warning');
                }

                $scope.loadingState = false;
            });
        };

        $scope.official();
    }]);

    // 拍照所需控制器
    myApp.controller('photoController', ['$scope', '$http', '$location', '$modal', 'photoService', 'utils', function ($scope, $http, $location, $modal, service, utils) {
        var planId, curExaminee;

        $scope.init = function () {
            $scope.loadingState = true;
            utils.decrypt($location.$$search.parameter).success(function (data) {
                if (data.resultType == 'Success') {
                    var result = JSON.parse(data.appendData);
                    planId = result.planId;
                    $scope.planName = result.planName;
                    $scope.getSceneList();
                } else {
                    utils.notify(data.message, 'warning');
                }

                $scope.loadingState = false;
            });
        };

        $scope.getSceneList = function (roomId, subjectId) {
            service.getSceneList(planId, roomId, subjectId).success(function (data) {
                angular.forEach(data, function (item) {
                    item.examSceneName += ' (' + utils.formatDate(item.planBeginTime) + ')';
                });

                $scope.sceneList = data;
                $scope.curScene = $scope.sceneList[0];

                $scope.getRoomList($scope.curScene.examSceneID);
            });
        };

        $scope.getRoomList = function (sceneId, subjectId) {
            service.getRoomList(planId, sceneId, subjectId).success(function (data) {
                data.unshift({ examRoomID: null, examRoomName: '全部考场' });

                $scope.roomList = data;
                $scope.curRoom = $scope.roomList[0];

                $scope.getStatusList();
            });
        };

        $scope.getStatusList = function () {
            var data = [{ statusId: null, statusName: '全部状态' }, { statusId: 0, statusName: '未拍照' }, { statusId: 1, statusName: '已拍照' }];
            $scope.statusList = data;
            $scope.curStatus = $scope.statusList[0];

            $scope.query();
        };

        $scope.query = function () {
            var curScene = $scope.curScene;
            var curRoom = $scope.curRoom;
            var curStatus = $scope.curStatus;
            var parameter = $scope.curParams;

            $scope.loadGrid(curScene.examSceneID, curRoom.examRoomID, curStatus.statusId, parameter);
        };

        $scope.loadGrid = function (sceneId, roomId, statusId, parameter) {
            $scope.loadingState = true;
            service.getList(planId, sceneId, roomId, statusId, parameter).success(function (data) {

                $scope.loadingState = false;
                if (data.resultType == 'Success') {
                    $scope.list = data.appendData;
                } else {
                    utils.notify(data.message, 'warning');
                }
            });
        };

        $scope.viewPhoto = function (model) {
            angular.forEach($scope.list, function (data, index, array) {
                if (data != model) data.active = false;
            });

            model.active = true;

            $scope.loadPhoto(model);
            curExaminee = model;
        }

        $scope.loadPhoto = function (model) {
            $('.photoImg').attr('src', '/Photo/GetStudentPhoto?planId=' + model.ExamPlanInfoID + '&sceneId=' + model.ExamSceneID + '&examineeId=' + model.ExamineeID + '&r=' + Math.random());
        }

        $scope.$root.$on('loadPhoto', function (event, data) {
            $scope.loadPhoto(data);
            // 切换当前状态为已拍照
            curExaminee.Photo = true;
        });

        $scope.camera = function () {
            if (curExaminee) {
                $modal.open({
                    templateUrl: '/App/views/Photo/Camera.html',
                    controller: 'camera',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        params: function () {
                            return { model: curExaminee, planId: planId };
                        }
                    }
                });
            } else {
                utils.notify('请先选择一个考生！', 'warning');
            }
        };

        $scope.init();
    }]);

    // Web拍照需要的控制器及方法列表
    myApp.controller('camera', ['$scope', '$routeParams', '$modalInstance', 'photoService', '$modal', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, $modal, utils, params, $filter) {
        var model = params.model, planId = params.planId;

        var methods = {
            loadCamera: function () {
                // 一寸：150*210
                // 原始：320*240
                var width = 320, height = 240, pos = 0, ctx, saveCB, image = [];

                // 获取canvas对象的引用
                //var canvas = document.getElementById('myCanvas');
                var canvas = document.createElement('canvas');
                canvas.setAttribute('width', width);
                canvas.setAttribute('height', height);

                if (canvas.toDataURL) {
                    // 获取canvas的2D绘图环境
                    ctx = canvas.getContext('2d');
                    // 复制画布上指定矩形的像素数据
                    image = ctx.getImageData(0, 0, width, height);
                    saveCB = function (data) {
                        var col = data.split(';');
                        var img = image;

                        for (var i = 0; i < width; i++) {
                            var tmp = parseInt(col[i]);
                            img.data[pos + 0] = (tmp >> 16) & 0xff;
                            img.data[pos + 1] = (tmp >> 8) & 0xff;
                            img.data[pos + 2] = tmp & 0xff;
                            img.data[pos + 3] = 0xff;
                            pos += 4;
                        }

                        if (pos >= 4 * width * height) {
                            // 将图像数据放回画布
                            ctx.putImageData(img, 0, 0);

                            // 新建一个 Canvas 截取一寸照片
                            var newImg = ctx.getImageData(85, 15, 150, 210);
                            var newCanvas = document.createElement('canvas');
                            newCanvas.setAttribute('width', 150);
                            newCanvas.setAttribute('height', 210);
                            var newCtx = newCanvas.getContext('2d');
                            newCtx.putImageData(newImg, 0, 0);

                            service.savePhoto(planId, model.ExamSceneID, model.ExamineeID, model.ExamCardNo, 'data', newCanvas.toDataURL('image/png')).success(function (data) {
                                if (data.resultType == 'Success') {
                                    utils.notify('成功拍照', 'success');
                                    $scope.$emit('loadPhoto', model);
                                    $scope.close();
                                } else {
                                    utils.notify(data.message, 'warning');
                                }
                            });
                            pos = 0;
                        }
                    };
                } else {
                    saveCB = function (data) {
                        image.push(data);

                        pos += 4 * width;

                        if (pos >= 4 * width * height) {
                            $.post('Manager/Photo/Upload', { type: 'pixel', data: image.join('|') });
                            pos = 0;
                        }
                    };
                }

                $('#camera').webcam({
                    width: width,
                    height: height,
                    mode: 'callback',
                    swffile: '/App/vendor/webcam/jscam.swf',
                    onTick: function () { },
                    onSave: saveCB,
                    onCapture: function () {
                        document.getElementById('shutter').play();

                        var flash = $('#flash');
                        flash.css('display', 'block');
                        flash.fadeOut('fast', function () {
                            flash.css('opacity', 1);

                            webcam.save();
                        });
                    },
                    debug: function (type, string) {
                        //$('#status').html(type + ': ' + string);
                        if (type.indexOf('error') > -1) {
                            if (string.indexOf('No camera was detected.') > -1 || string.indexOf('Flash movie not yet registered!') > -1)
                                utils.notify('没有检测到相机。', 'warning');
                            else
                                utils.notify(string, 'warning');
                        }
                    },
                    onLoad: function () {
                        var cams = webcam.getCameraList();
                        if (cams.length > 0) {
                            utils.notify('当前系统支持摄像功能！', 'success');
                        } else {
                            utils.notify('当前系统不支持摄像功能！', 'warning');
                        }
                    }
                });
            },
            shoot: function () {
                webcam.capture();
            },
            close: function () {
                $modalInstance.close(true);
            }
        };

        angular.extend($scope, methods);

        setTimeout(function () { $scope.loadCamera(); }, 600);
    }]);
})();